package com.rabbit.config;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.rabbit.constant.SecurityConstant;
import com.rabbit.db.entity.Role;
import com.rabbit.db.entity.User;
import com.rabbit.mapper.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zjw
 * @date 2022/01/15 19:03
 */
@Component
@Slf4j
public class SaTokenInterfaceConfig implements StpInterface {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return new ArrayList<>();
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        String token = StpUtil.getTokenValue();
        SaSession saSession = StpUtil.getTokenSessionByToken(token);
        return saSession.get(SecurityConstant.LOGIN_ROLE, () -> {
            User user = (User) saSession.get(SecurityConstant.LOGIN_USER);
            List<Role> roles = roleMapper.queryUserRole(user);
            return roles.stream().map(Role::getRoleKey).collect(Collectors.toList());
        });
    }
}
